﻿using System;
using System.Linq;
using MS.InformationManagement.Presenter.Support;
using MS.InformationManagement.Presenter.TRDConfigGrid;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using MS.InformationManagement.Support;
using System.Text;
using System.Web.UI;
using MS.InformationManagement.Support.Constants;

namespace MS.InformationManagement.WP.RecordCenter.TRDConfigGrid
{
    public partial class TRDConfigGridUserControl : BaseControl, ITRDConfigGridView
    {
        #region [Event Handlers]

        protected void btnExportPending_Click(object sender, EventArgs e)
        {
            _Presenter.ExportPendingSections();
        }

        protected void btnExportHistoric_Click(object sender, EventArgs e)
        {
            _Presenter.ExportTRDHistory();
        }

        protected void btnExportTRD_Click(object sender, EventArgs e)
        {
            _Presenter.ExportTRDItems();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Page.RegisterAjaxLoaderPlugin();
            GenerateRequiredJavascript();

            ddlFondo.Required("Seleccione un valor para esta lista desplegable", "vgSearch", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            ddlSeccion.Required("Seleccione un valor para esta lista desplegable", "vgSearch", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);
            ddlSubseccion.Required("Seleccione un valor para esta lista desplegable", "vgSearch", AjaxControlToolkit.ValidatorCalloutPosition.BottomRight);

            OnBackdropChange += new Presenter.TRDConfigGrid.Events.BackdropChangeHandler(TRDConfigGridUserControl_OnBackdropChange);
            OnSectionChange += new Presenter.TRDConfigGrid.Events.SectionChangeHandler(TRDConfigGridUserControl_OnSectionChange);
            OnSuccess += new Presenter.Support.Events.SuccessHandler(TRDConfigGridUserControl_OnSuccess);
            OnError += new Presenter.Support.Events.ErrorHandler(TRDConfigGridUserControl_OnError);

            trdItemsPager.OnPageChanged += new InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Pager.PageChangeHandler(trdItemsPager_OnPageChanged);
            historyPager.OnPageChanged += new InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Pager.PageChangeHandler(historyPager_OnPageChanged);
            nonConfiguredPager.OnPageChanged += new InformationManagement.Controls._CONTROLTEMPLATES.InformationManagerControls.Pager.PageChangeHandler(nonConfiguredPager_OnPageChanged);

            trdItemsPager.NumberOfPagesToDisplay = 10;
            historyPager.NumberOfPagesToDisplay = 10;
            nonConfiguredPager.NumberOfPagesToDisplay = 10;

            TrdItemsPageSize = 10;
            HistoryItemsPageSize = 10;
            NonConfiguredSectionsPageSize = 10;

            TrdItemsPageIndex = 0;
            HistoryItemsPageIndex = 0;
            NonConfiguredSectionsPageIndex = 0;

            try
            {
                _Presenter = new TRDConfigGridPresenter(this);
                _Presenter.HandlerLoad();
                nonConfiguredPager.BuildPager();
            }
            catch (Exception ex)
            {
                OnError(this, ex);
            }

            btnFilter.AddLoader();
            ddlFondo.AddLoader();
            ddlSeccion.AddLoader();
        }

        protected void nonConfiguredPager_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            if (Section != null && Subsection != null)
            {
                _Presenter.ReloadHistoryItems();
                historyPager.BuildPager();
                _Presenter.ReloadTRDConfigItems();
                trdItemsPager.BuildPager();                
            }
            _Presenter.ReloadNonConfiguredSections();
            nonConfiguredPager.BuildPager();
            
        }

        protected void historyPager_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            _Presenter.ReloadHistoryItems();
            historyPager.BuildPager();
            _Presenter.ReloadNonConfiguredSections();
            nonConfiguredPager.BuildPager();
            _Presenter.ReloadTRDConfigItems();
            trdItemsPager.BuildPager();
        }

        protected void trdItemsPager_OnPageChanged(object sender, Controls.PageChangeEventArgs e)
        {
            _Presenter.ReloadHistoryItems();
            historyPager.BuildPager();
            _Presenter.ReloadNonConfiguredSections();
            nonConfiguredPager.BuildPager();
            _Presenter.ReloadTRDConfigItems();
            trdItemsPager.BuildPager();
        }

        protected void TRDConfigGridUserControl_OnError(object sender, Exception e)
        {
            HandleError(e);
        }

        protected void TRDConfigGridUserControl_OnSuccess(object sender, EventArgs e)
        {
            HandleSuccess("Operación realizada sin ningún problema", null);
        }

        protected void ddlFondo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!ddlFondo.SelectedValue.Equals("0"))
                OnBackdropChange(sender, e);
        }

        protected void ddlSeccion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!ddlSeccion.SelectedValue.Equals("0"))
                OnSectionChange(sender, e);
        }

        protected void TRDConfigGridUserControl_OnSectionChange(object sender, EventArgs e)
        {
            try
            {                
                _Presenter.LoadSubsections();
            }
            catch (Exception ex)
            {
                OnError(this, ex);
            }
        }

        protected void TRDConfigGridUserControl_OnBackdropChange(object sender, EventArgs e)
        {
            try
            {                
                _Presenter.LoadBackdropChilds();
            }
            catch (Exception ex)
            {
                OnError(this, ex);
            }
        }

        protected void btnFilter_Click(object sender, EventArgs e)
        {
            try
            {                
                _Presenter.LoadTRDConfigItems();
                trdItemsPager.BuildPager();
                historyPager.BuildPager();
                nonConfiguredPager.BuildPager();
            }
            catch (Exception ex)
            {
                OnError(sender, ex);
            }
        }

        protected void Literal1_DataBinding(object sender, EventArgs e)
        {
            Literal trigger = sender as Literal;
            HtmlAnchor javascriptTrigger = trigger.Parent.FindControl("ajscriptTrigger") as HtmlAnchor;
            if (trigger.Text.Length > 55) { trigger.Text = string.Concat(trigger.Text.Substring(0, 55), "..."); }
            else { javascriptTrigger.Visible = false; }
        }

        protected void hpl_DataBinding(object sender, EventArgs e)
        {
            //Literal trigger = sender as Literal;
            HtmlAnchor javascriptTrigger = sender as HtmlAnchor;
            if (javascriptTrigger != null)
            {
                javascriptTrigger.Attributes.Add("onclick", string.Format("showFullText(this, '{0}');", javascriptTrigger.Name));
                javascriptTrigger.HRef = "javascript:void(0);";
            }
        }

        protected void spgrdTRDConfig_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
            {
                if (((Microsoft.SharePoint.WebControls.SPGridViewRow)(e.Row)).HeaderText != null)
                    ((Microsoft.SharePoint.WebControls.SPGridViewRow)(e.Row)).HeaderText = ((Microsoft.SharePoint.WebControls.SPGridViewRow)(e.Row)).HeaderText.Replace(";#", " ");
            }

        }

        #endregion

        #region [ITRDConfigGridView Members]

        public void ExportToCsv(string fileName, string fileContent)
        {
            Response.Clear();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "application/csv";
            Response.ContentEncoding = System.Text.Encoding.Unicode;
            Response.AddHeader("content-disposition", string.Format("attachment; filename={0}.csv", fileName));
            Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
            Response.Write(fileContent);
            Response.Flush();
            Response.End();
        }

        public object TRDConfigItems
        {
            get
            {
                return Cache["TRDConfigItems"];
            }
            set
            {
                Cache["TRDConfigItems"] = value;
                spgrdTRDConfig.DataSource = value;
                spgrdTRDConfig.DataBind();
            }
        }

        public object HistoricTRDConfigItems
        {
            get
            {
                return Cache["HistoricTRDConfigItems"];
            }
            set
            {
                Cache["HistoricTRDConfigItems"] = value;
                spgrdTRDConfigHistory.DataSource = value;
                spgrdTRDConfigHistory.DataBind();
            }
        }

        public System.Collections.Generic.IEnumerable<DAL.RecordCenter.FondosFondo> Backdrops
        {
            get
            {
                return ddlFondo.DataSource as System.Collections.Generic.IEnumerable<DAL.RecordCenter.FondosFondo>;
            }
            set
            {
                ddlFondo.DataSource = value;
                ddlFondo.DataBind();
            }
        }

        public System.Collections.Generic.IEnumerable<DAL.RecordCenter.FondosFondo> ChildBackdrops
        {
            get
            {
                return Cache["ChildBackdrops"] as System.Collections.Generic.IEnumerable<DAL.RecordCenter.FondosFondo>;
            }
            set
            {
                Cache["ChildBackdrops"] = value.ToList();
                ddlSubfondo.Items.Clear();
                ddlSubfondo.DataSource = value;
                ddlSubfondo.DataBind();
                ddlSubfondo.Items.Insert(0, new ListItem { Text = "----Seleccione----", Value = "0" });

            }
        }

        public System.Collections.Generic.IEnumerable<DAL.RecordCenter.SeccionesSeccion> Sections
        {
            get
            {
                return ddlSeccion.DataSource as System.Collections.Generic.IEnumerable<DAL.RecordCenter.SeccionesSeccion>;
            }
            set
            {
                ddlSeccion.DataSource = value;
                ddlSeccion.DataBind();
            }
        }

        public System.Collections.Generic.IEnumerable<DAL.RecordCenter.SeccionesSeccion> Subsections
        {
            get
            {
                return Cache["Subsections"] as System.Collections.Generic.IEnumerable<DAL.RecordCenter.SeccionesSeccion>;
            }
            set
            {
                Cache["Subsections"] = value.ToList();
                ddlSubseccion.Items.Clear();
                ddlSubseccion.DataSource = value;
                ddlSubseccion.DataBind();
                ddlSubseccion.Items.Insert(0, new ListItem { Text = "----Seleccione----", Value = "0" });
            }
        }

        public System.Collections.Generic.IEnumerable<DAL.RecordCenter.SeccionesSeccion> NonConfiguredSections
        {
            get
            {
                return Cache["NonConfiguredSections"] as System.Collections.Generic.IEnumerable<DAL.RecordCenter.SeccionesSeccion>;
            }
            set
            {
                Cache["NonConfiguredSections"] = value;
                spgrdNonConfigured.DataSource = value;
                spgrdNonConfigured.DataBind();
            }
        }

        public DAL.RecordCenter.FondosFondo Backdrop
        {
            get
            {
                int backdropId = Convert.ToInt32(ddlFondo.SelectedValue);
                DAL.RecordCenter.FondosFondo selectedBackdrop = Backdrops.SingleOrDefault(b => b.Id.Equals(backdropId));
                return selectedBackdrop;
            }
            set
            {
                ddlFondo.SelectedValue = value.Id.ToString();
                OnBackdropChange(value, null);
            }
        }

        public DAL.RecordCenter.FondosFondo ChildBackdrop
        {
            get
            {
                int backdropChildId = Convert.ToInt32(ddlSubfondo.SelectedValue);
                DAL.RecordCenter.FondosFondo selectedBackdropChild = ChildBackdrops.SingleOrDefault(bc => bc.Id.Equals(backdropChildId));
                return selectedBackdropChild;
            }
            set
            {
                ddlSubfondo.SelectedValue = value.Id.ToString();
            }
        }

        public DAL.RecordCenter.SeccionesSeccion Section
        {
            get
            {
                int sectidId = Convert.ToInt32(ddlSeccion.SelectedValue);
                DAL.RecordCenter.SeccionesSeccion selectedSection = Sections.SingleOrDefault(s => s.Id.Equals(sectidId));
                return selectedSection;
            }
            set
            {
                ddlSeccion.SelectedValue = value.Id.ToString();
            }
        }

        public DAL.RecordCenter.SeccionesSeccion Subsection
        {
            get
            {
                int subsectionId = Convert.ToInt32(ddlSubseccion.SelectedValue);
                DAL.RecordCenter.SeccionesSeccion selectedSubsection = Subsections.SingleOrDefault(sbs => sbs.Id.Equals(subsectionId));
                return selectedSubsection;
            }
            set
            {
                ddlSubseccion.SelectedValue = value.Id.ToString();
            }
        }

        public event Presenter.TRDConfigGrid.Events.BackdropChangeHandler OnBackdropChange;

        public event Presenter.TRDConfigGrid.Events.SectionChangeHandler OnSectionChange;

        public new event Presenter.Support.Events.ErrorHandler OnError;

        public event Presenter.Support.Events.SuccessHandler OnSuccess;

        public int TrdItemsPageIndex
        {
            get
            {
                return trdItemsPager.PageIndex;
            }
            set
            {
                trdItemsPager.PageIndex = value;
            }
        }

        public int TrdItemsPageSize
        {
            get
            {
                return trdItemsPager.PageSize;
            }
            set
            {
                trdItemsPager.PageSize = value;
            }
        }

        public int TrdItemsTotalRecords
        {
            get
            {
                return trdItemsPager.TotalRecords;
            }
            set
            {
                trdItemsPager.TotalRecords = value;
            }
        }

        public int HistoryItemsPageIndex
        {
            get
            {
                return historyPager.PageIndex;
            }
            set
            {
                historyPager.PageIndex = value;
            }
        }

        public int HistoryItemsPageSize
        {
            get
            {
                return historyPager.PageSize;
            }
            set
            {
                historyPager.PageSize = value;
            }
        }

        public int HistoryItemsTotalRecords
        {
            get
            {
                return historyPager.TotalRecords;
            }
            set
            {
                historyPager.TotalRecords = value;
            }
        }

        public int NonConfiguredSectionsPageIndex
        {
            get
            {
                return nonConfiguredPager.PageIndex;
            }
            set
            {
                nonConfiguredPager.PageIndex = value;
            }
        }

        public int NonConfiguredSectionsPageSize
        {
            get
            {
                return nonConfiguredPager.PageSize;
            }
            set
            {
                nonConfiguredPager.PageSize = value;
            }
        }

        public int NonConfiguredSectionsTotalRecords
        {
            get
            {
                return nonConfiguredPager.TotalRecords;
            }
            set
            {
                nonConfiguredPager.TotalRecords = value;
            }
        }

        #endregion

        #region [Private Members]

        private void GenerateRequiredJavascript()
        {
            StringBuilder javascriptBuilder = new StringBuilder("<script type='text/javascript'>");
            javascriptBuilder
                .Append("function openNewItemPopUp() {")
                .Append("var formIsValid = Page_ClientValidate('vgSearch');")
                .Append("if (formIsValid === true) {")
                .Append("var url ='")
                .Append(string.Format("{0}/_layouts/MS.InformationManagement.WP/TRDItemConfig.aspx?bdID='+", SPContext.Current.Web.Url))
                .Append(string.Format("document.getElementById('{0}').value+'&bdcID='+", ddlFondo.ClientID))
                .Append(string.Format("document.getElementById('{0}').value+'&sID='+", ddlSubfondo.ClientID))
                .Append(string.Format("document.getElementById('{0}').value+'&sbID='+", ddlSeccion.ClientID))
                .Append(string.Format("document.getElementById('{0}').value;", ddlSubseccion.ClientID))
                .Append("var modalOptions = {")
                .Append("title: 'Agregar un elemento de configuración',")
                .Append("url: url,")
                .Append("allowMaximize: false,")
                .Append("showClose: true,")
                .Append("autoSize: true,")
                .Append("dialogReturnValueCallback: onDialogClose")
                .Append("};")
                .Append("SP.UI.ModalDialog.showModalDialog(modalOptions);")
                .Append("}")
                .Append("}")
                .Append("function onDialogClose(dialogResult, returnValue) {")
                .Append("switch (dialogResult) {")
                .Append("case SP.UI.DialogResult.cancel:")
                .Append("break;")
                .Append("case SP.UI.DialogResult.OK:")
                .Append(string.Format("document.getElementById('{0}').click();", btnFilter.ClientID))
                .Append("break;")
                .Append("default:")
                .Append("break;")
                .Append("}")
                .Append("}")
                .Append("function openEditItemPopUp(id){")
                 .Append("var url ='")
                .Append(string.Format("{0}/_layouts/MS.InformationManagement.WP/TRDItemConfig.aspx?id='+", SPContext.Current.Web.Url))
                .Append("id")
                .Append("+'&strategy=Edit';")
                .Append("var modalOptions = {")
                .Append("title: 'Editar un elemento de configuración',")
                .Append("url: url,")
                .Append("allowMaximize: false,")
                .Append("showClose: true,")
                .Append("autoSize: true,")
                .Append("dialogReturnValueCallback: onDialogClose")
                .Append("};")
                .Append("SP.UI.ModalDialog.showModalDialog(modalOptions);")
                .Append("}")
                .Append("function openNewItemPopUpGrid(sectionId, subSectionId) {")
                .Append(string.Format("var selIndexSubSec = document.getElementById('{0}').value;", ddlSubseccion.ClientID))
                .Append(string.Format("var selIndexSubFon = document.getElementById('{0}').value;", ddlSubfondo.ClientID))
                .Append("if(selIndexSubSec == 0 || selIndexSubFon ==0){")    
                .Append("alert('Debe seleccionar un fondo, subfondo,sección y subsección antes de ejecutar esta acción');")
                .Append("}")
                .Append("else{")
                .Append("var url ='")
                .Append(string.Format("{0}/_layouts/MS.InformationManagement.WP/TRDItemConfig.aspx?bdID='+", SPContext.Current.Web.Url))
                .Append(string.Format("document.getElementById('{0}').value+'&bdcID='+", ddlFondo.ClientID))
                .Append(string.Format("document.getElementById('{0}').value+'&sID='+sectionId+'&sbID='+subSectionId;", ddlSubfondo.ClientID))
                .Append("var modalOptions = {")
                .Append("title: 'Agregar un elemento de configuración',")
                .Append("url: url,")
                .Append("allowMaximize: false,")
                .Append("showClose: true,")
                .Append("autoSize: true,")
                .Append("dialogReturnValueCallback: onDialogClose")
                .Append("};")
                .Append("SP.UI.ModalDialog.showModalDialog(modalOptions);")
                .Append("} }")
                .Append("function exportTRDItems(){")
                .Append(string.Format( "var bID= document.getElementById('{0}').value;", ddlFondo.ClientID))
                .Append(string.Format( "var bcID= document.getElementById('{0}').value;", ddlSubfondo.ClientID))
                .Append(string.Format("var sID= document.getElementById('{0}').value;", ddlSeccion.ClientID))
                .Append(string.Format("var sbID= document.getElementById('{0}').value;", ddlSubseccion.ClientID))
                .Append("if(bID == '0' || bID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar un fondo', 'yellow', 6000); return; }")
                .Append("if(bcID == '0' || bcID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar un subfondo', 'yellow', 6000); return; }")
                .Append("if(sID == '0' || sID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar una seccion', 'yellow', 6000); return; }")
                .Append("if(sbID == '0' || sbID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar una subseccion', 'yellow', 6000); return; }")
                .Append("var url = '/sites/docs/_layouts/Ms.InformationManagement.WP/ExportHandler.ashx?action=trdconfigdata&bID='+bID+'&bcID='+bcID+'&sID='+sID+'&sbID='+sbID;")
                .Append("window.open(url, '_blank');}")
                .Append("function exportHistoricTRDItems(){")
                .Append(string.Format("var bID= document.getElementById('{0}').value;", ddlFondo.ClientID))
                .Append(string.Format("var bcID= document.getElementById('{0}').value;", ddlSubfondo.ClientID))
                .Append(string.Format("var sID= document.getElementById('{0}').value;", ddlSeccion.ClientID))
                .Append(string.Format("var sbID= document.getElementById('{0}').value;", ddlSubseccion.ClientID))
                .Append("if(bID == '0' || bID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar un fondo', 'yellow', 6000); return; }")
                .Append("if(bcID == '0' || bcID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar un subfondo', 'yellow', 6000); return; }")
                .Append("if(sID == '0' || sID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar una seccion', 'yellow', 6000); return; }")
                .Append("if(sbID == '0' || sbID == ''){ MS.InformationManagement.Common.ShowStatus('Debe seleccionar una subseccion', 'yellow', 6000); return; }")
                .Append("var url = '/sites/docs/_layouts/Ms.InformationManagement.WP/ExportHandler.ashx?action=trdhistoricdata&bID='+bID+'&bcID='+bcID+'&sID='+sID+'&sbID='+sbID;")
                .Append("window.open(url, '_blank');}")
                .Append("</script>");
            ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "functions", javascriptBuilder.ToString(), false);
        }

        TRDConfigGridPresenter _Presenter;

        #endregion        
    }
}
